package com.biz.hunter.dao;

import java.util.Collections;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.biz.hunter.db.entity.UserInfo;
import com.biz.hunter.dbutil.BaseDAO;
import com.biz.qq.wechat.api.UserManagementAPI;                      

@Repository
public class WXUserDAO {
	Logger logger = LoggerFactory.getLogger(WXUserDAO.class);

	private static final String SQL_SAVE = "insert into wx_userinfo(openid,nickname,sex,language,"
			+ "city,province,country,headimgurl,subscribe,subscribe_time) values(?,?,?,?,?,?,?,?,?,?)";
	private static final String SQL_DELETE = "delete from wx_userinfo where openid=?";
	private static final String SQL_GET_LIST = "select openid,nickname,sex,language,"
			+ "city,province,country,headimgurl,subscribe,subscribe_time from wx_userinfo where openid in (";
	private static final String SQL_GET = "select openid,nickname,sex,language,"
			+ "city,province,country,headimgurl,subscribe,subscribe_time from wx_userinfo where openid = ?";
	private static final String SQL_UPDATE = "update wx_userinfo set nickname=?"
			+ ",sex=?, language=?,city=?,province =?,country=?,headimgurl=?,subscribe=? ,subscribe_time=? where openid =?";

	private static final String SQL_OPENID = "insert into wx_userinfo(openid,subscribe,subscribe_time) values(?,?,?)";

	public int saveOpenid(String openId,int subscribe,Long subscribeTime) {
		return BaseDAO.execute(SQL_OPENID, openId, subscribe, subscribeTime);
	}

	public int save(UserInfo... users) {
		if (users != null) {
			if (users.length == 1) {
				UserInfo user = users[0];
				return BaseDAO.execute(SQL_SAVE, user.getOpenid(),
						user.getNickname(), user.getSex(), user.getLanguage(),
						user.getCity(), user.getProvince(), user.getCountry(),
						user.getHeadimgurl(), user.getSubscribe(),
						user.getSubscribe_time());

			} else {
				Object[][] params = new Object[users.length][9];
				int i = 0;
				for (UserInfo user : users) {
					params[i][0] = user.getOpenid();
					params[i][1] = user.getNickname();
					params[i][2] = user.getSex();
					params[i][3] = user.getLanguage();
					params[i][4] = user.getCity();
					params[i][5] = user.getCountry();
					params[i][6] = user.getHeadimgurl();
					params[i][7] = user.getSubscribe();
					params[i][8] = user.getSubscribe_time();
					i++;
				}
				int[] rows = BaseDAO.batch(SQL_SAVE, params);
				if (rows != null && rows.length > 0) {
					int total = 0;
					for (int r : rows) {
						total += r;
					}
					return total;
				} else {
					return -1; // 数据库访问异常�?
				}
			}
		} else {
			return 0;
		}
	}

	public int delete(String openId) {
		if (StringUtils.isEmpty(openId)) {
			return -1;
		}
		return BaseDAO.execute(SQL_DELETE, openId);

	}

	public List<UserInfo> get(String... userIds) {

		if (userIds != null) {
			StringBuilder sql = new StringBuilder(SQL_GET_LIST);
			boolean start = false;
			for (String id : userIds) {
				if (start) {
					sql.append(",").append(id);
				} else {
					start = true;
					sql.append(id);
				}
			}
			sql.append(")");
			return BaseDAO.queryForList(UserInfo.class, sql.toString());

		} else {
			return Collections.emptyList();
		}
	}

	public int update(UserInfo user) {
		return BaseDAO.execute(SQL_UPDATE, user.getNickname(), user.getSex(),
				user.getLanguage(), user.getCity(), user.getProvince(),
				user.getCountry(), user.getHeadimgurl(), user.getSubscribe(),
				user.getSubscribe_time(), user.getOpenid());
	}

	public UserInfo getByOpenId(String openid) {
		return BaseDAO.queryForObject(UserInfo.class, SQL_GET, openid);
	}

	public UserInfo subscribe(String openid, String token) {
		UserInfo userInfo = UserManagementAPI.getUserInfo(openid,token);
		if (userInfo == null) {
			logger.error("did not get user's INFO" + openid);
			return null;
		}
		UserInfo user = getByOpenId(openid);
		if (user == null) {
//			if (user.getNickname()!=null) {
//				user.setNickname(Base64.encodeBase64(user.getNickname().getBytes()).toString());;
//			}
			logger.info("save userinfo" + userInfo.getOpenid());
			int result = save(userInfo);
			if (result == -1) {
				logger.error("did not save the user into DB " + openid);
				return null;
			}
		} else {
			int result = update(userInfo);
			if (result == -1) {
				logger.error("did not update the user into DB " + openid);
				return null;
			}

		}
		return userInfo;
	}

	public int unSubscribe(String openId) {
		int result = -1;
		result = delete(openId);
		return result;
	}
}
